//messageIDs
//更新队列在线状态
var UpdateQueueStatus = "STS_Update_Queue_Status";
//分诊台队列的过号人数变化信息
var UpdateQueuePassNum = "STS_Update_Queue_Pass_Num";
//分诊台队列的已就诊人数变化消息
var UpdateEndNum = "STS_Update_Queue_End_Num";
//更新分诊台队列候诊患者数量
var UpdateQueueWaitNum = "STS_Update_Queue_Wait_Num";
//医生点击下一位时，分诊台队列的候诊人数变化和分诊台队列的已就诊人数变化
var UpdateQueueWaitEndNum = "STS_Update_Queue_Wait_End_Num";
//分诊台点击过号召回时,发送分诊台队列的候诊数目，过号数目变化
var UpdateQueueWaitPassNum = "STS_Update_Queue_Wait_Pass_Num";
//更新预检状态
var UpdateSystemPretestStatus = "STS_Update_System_config";


//分诊台系统的过号人数变化信息
var UpdateSystemPassNum = "STS_Update_System_Pass_Num";
//分诊台系统的已就诊人数变化消息
var UpdateSystemEndNum = "STS_Update_System_End_Num";
//更新分诊台所选系统候诊患者数量
var UpdateSystemWaitNum = "STS_Update_System_Wait_Num";
//更新分诊台系统候诊患者数量
var UpdateSystemWaitEndNum = "STS_Update_System_Wait_End_Num";
//分诊台点击过号召回时,发送分诊台系统的候诊数目，过号数目变化
var UpdateSystemWaitPassNum = "STS_Update_System_Wait_Pass_Num";
//医生停诊
var NurseDoctorWriteOff = "nurse_doctor_wirte_off";


//账号在其他终端登录
var ForcedLoginOut = "STS_Compel_LoginOut";

//更新右下角候诊、过号、已就诊数量
var _UpdateNumbers = STSUrl + "/TriageSysQueue/getPatientAcountBySysId";
var _ReqCallSystemListUrl = STSUrl + "/TriageSysQueue/getSysByTriageId";
var _QueryQueueBySystemIdUrl = STSUrl + "/TriageSysQueue/getQueueBySysIdStatus";
var _GetHospitalInfoUrl = OrgUrl + "/Hospital/getHospitalList";
var _QueryPatInfoUrl = STSUrl + "/TriageSysQueue/getSTSPatientByPatientKey";
var ajaxSearchUrl = STSUrl + '/TriageSysQueue/getSTSPatientByKeyOrName';

//系统ID
var _sysId = "";
// 选中系统的科室id
var _sysDeptId = "";
// 当前选中的队列id，用于选中队列后，切换到排版的存储
var _selectedQueueId = "";
//平铺或者列表标记
var listType = "list";
var queueId2StatusMap = {};
var g_currentTab = "";
$(function () {
    $('.mask').on('click',function () {
        $(this).hide();
        $('#search-list').hide().find('.mui-search-body').html('');
        $('#text_patinfo').val('');
    });
    $('#search-list').on('click','.mui-search-body li',function () {
        var params = $(this).parents('ul').data();
        localStorage.setItem("_P_KEY_", params.id);
        var _systemId = allOrSingleSystemId();
        $('#search-list').hide().find('.mui-search-body').html('');
        $('#text_patinfo').val('');
        $('.mask').hide();
        var queueObject = {
            queueId:params.queueid,
            systemId:_systemId,
            queueKey:params.queuingkey,
        };
        /**
         *  如果根据患者姓名查出多个，默认选中第一个
         * */
        if(params.form==0){
            // 未分诊患者
            if($("#select_call_systemType").val()=="全部"){
                var data = $('#sysId_'+_systemId).data();
                notSplitDiaOptAll(0,_systemId,data.deptid,data.pretest);
            } else{
                notSplitDiaOpt(0);
            }
        }else if(params.form==1){
            //已分诊患者
            //候诊   1 候诊 2 诊室等候 3 就诊中  4 已就诊
            if (params.treatmentstage == 1 || params.treatmentstage == 2) {
                //alert("候诊---->" + _treatmentStage);
                AutoSelectQueue(queueObject);
                $('#d_right_content').html('<iframe id="patient_tmt_info" scrolling="no" src="./nurse_mgr/patient_tmt_info.html?idx=wait"></iframe>');
            }
            //已接诊
            else if (params.treatmentstage == 3 || params.treatmentstage == 4) {
                AutoSelectQueue(queueObject);
                $('#d_right_content').html('<iframe id="patient_tmt_info" scrolling="no" src="./nurse_mgr/patient_tmt_info.html?idx=yjz"></iframe>');
            }
        }else {
            AutoSelectQueue(queueObject);
            $('#d_right_content').html('<iframe id="patient_tmt_info" scrolling="no" src="./nurse_mgr/patient_tmt_info.html?idx=wbd"></iframe>');
        }
    })
});

//半全局搜索
function queryPatInfo() {
    var _queryVal = $("#text_patinfo").val();
    var _systemId = allOrSingleSystemId();
    if (_queryVal.trim() == "")  return layer.alert("请输入有效的患者信息", { icon: 2 });
    $.ajax({
        url: ajaxSearchUrl,
        type: 'get',
        data: {
            searchKey: _queryVal,
            systemId: _systemId
        },
        success: function (d) {
            var res = JSON.parse(d);
            if (res.status == 0) {
                var frag = dealAllPatients(res.signList,0);// 未分诊患者
                frag += dealAllPatients(res.queuingList,1);// 已分诊患者
                frag += dealAllPatients(res.noSignList,2);// 未报到患者
                if(frag!=''){
                    $('.mask').show();
                    $('#search-list').show().find('.mui-search-body').html(frag);
                }else {
                    layer.alert('此系统内没有查到对应的患者', { icon: 7 });
                }
            }else {
                layer.alert(res.desc, { icon: 7 });
            }
        },
        error: function () {
            layer.msg('操作失败',{icon:7});
        }
    });
}
function dealAllPatients(arr,form) {
    arr = arr || [];
    var frag = '';
    for (var i = 0;i<arr.length;i++){
        frag +='<ul id="pid_'+(arr[i]['id']||arr[i]['signId'])+'"  class="clearfix" data-form="'+form+'" data-id="'+(arr[i]['id']||arr[i]['signId'])+'"  data-treatmentStage="'+(arr[i]['treatmentStage']||'')+'" data-queueId="'+(arr[i]['queueId']||'')+'" data-queuingKey="'+(arr[i]['queuingKey']||'')+'">'
        frag +='<li>'+(arr[i]['registerId']||'')+'</li>';// 就诊号
        frag +='<li>'+(arr[i]['patientName']||'')+'</li>';// 姓名
        frag +='<li>'+(formatTimer(arr[i]['registerTime']))+'</li>';// 挂号时间
        frag +='</ul>';// 挂号时间
    }
    return frag;
}
function formatTimer(str) {
    str = str ||'';
    if(str=='') return '';
    return str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, "$1-$2-$3 $4:$5:$6");
}
//查询后自动选择队列
function AutoSelectQueue(queueObj) {
    if($("#select_call_systemType").val()=="全部"){
        $(".listQuqueStatus").find('input').each(function(){
            if($(this).attr("data-systemId")== queueObj.systemId){
                var _sysDeptId= $(this).attr("data-deptId");
                var _preTest= $(this).attr("data-preTest");
                localStorage.deptIdAll = _sysDeptId;
                updateColorButtonsVisible(_preTest);

            }
        });
    }
    localStorage.queueId = queueObj.queueId;
    localStorage.systemId = queueObj.systemId;
    localStorage.queueKey = queueObj.queueKey;
    var queueDom = $("#" + queueObj.queueId + "_text").parent();
    //alert(queueDom.html());
    //切换样式
    loadSimpleDocTypeHeaderStype(queueDom);
    $(".expand_conent").css({"border": "1px solid #cccccc"});
    $(".expand_conent").each(function () {
        if ($(this).attr("data-queueId") ==  queueObj.queueId) {
            $(this).css({"border": "1px solid #19ADFF"});
        }
    });
}
/**
 * 获取医院的名称
 */
function getHospitalInfo() {

    $.ajax({
        url: _GetHospitalInfoUrl,
        type: 'get',
        success: function (data) {
            var result = JSON.parse(data);
            if (result.status == '0') {
                var dataInfo = result.data;
                if (dataInfo.length > 0) {
                    var dataItems = JSON.parse(dataInfo);
                    $.each(dataItems, function (index) {
                        localStorage.hospitalName = dataItems[index].hospitalName;
                    });
                }

            }
        }
    });
}

/**
 * 加载分诊台页面的第一个页面
 */
function loadTheFristPage() {
    //加载系统类型
    loadCallSystemTypeList();
    //加载用户信息
    loadUserInfo();
}

//分诊台重置显示通道
function Reset_RabbitMQ_Body_Nurse(message) {
    var jsonStr = JSON.stringify(message);
    var jsonPar = JSON.parse(jsonStr);
    var messageContentObj = JSON.parse(jsonPar.msgContent);

    var msgID = jsonPar.msgId;
    if (msgID != null && msgID != undefined) {
        if (msgID == UpdateQueueStatus) {
            queueId2StatusMap[messageContentObj.queueId] = messageContentObj.onLineStatus;
            Reset_STS_Update_Queue_Status(messageContentObj.systemId, messageContentObj.queueId, messageContentObj.onLineStatus, listType);
        } else if (msgID == UpdateQueuePassNum) {
            Reset_Queue_After_Num_Nurse(messageContentObj.queueId, messageContentObj.overFlowPatientCount);
            refreshByRabbit(messageContentObj.queueId);
        } else if (msgID == UpdateEndNum) {
            Reset_Queue_Accept_Num_Nurse(messageContentObj.queueId, messageContentObj.treatedPatientCount);
            refreshByRabbit(messageContentObj.queueId);
        } else if (msgID == UpdateQueueWaitNum) {
            Reset_Queue_Wait_Num_Nurse(messageContentObj.queueId, messageContentObj.waitPatientCount);
            refreshByRabbit(messageContentObj.queueId);
        } else if (msgID == UpdateQueueWaitEndNum) {
            Reset_Queue_Wait_End_Num_Nurse(messageContentObj.queueId, messageContentObj.waitPatientCount,
                messageContentObj.treatedPatientCount);
            refreshByRabbit(messageContentObj.queueId);
        } else if (msgID == UpdateQueueWaitPassNum) {
            Reset_Queue_Wait_Pass_Num_Nurse(messageContentObj.queueId, messageContentObj.waitPatientCount,
                messageContentObj.overFlowPatientCount);
            refreshByRabbit(messageContentObj.queueId);
        } else if (msgID == UpdateSystemPassNum) {
            Reset_System_After_Num_Nurse(messageContentObj.systemId, messageContentObj.overFlowPatientCount);
        } else if (msgID == UpdateSystemEndNum) {
            Reset_System_Accept_Num_Nurse(messageContentObj.systemId, messageContentObj.treatedPatientCount);
        } else if (msgID == UpdateSystemWaitNum) {
            Reset_System_Wait_Num_Nurse(messageContentObj.systemId, messageContentObj.waitPatientCount);
        } else if (msgID == UpdateSystemWaitEndNum) {
            Update_System_Wait_End_Num(messageContentObj.systemId, messageContentObj.waitPatientCount,
                messageContentObj.treatedPatientCount);
        } else if (msgID == UpdateSystemWaitPassNum) {
            Update_System_Wait_Pass_Num(messageContentObj.systemId, messageContentObj.waitPatientCount,
                messageContentObj.overFlowPatientCount);
        } else if (msgID == NurseDoctorWriteOff) {
            Doctor_Write_Off(messageContentObj.deptName, messageContentObj.callingRelationObjName,
                messageContentObj.doctorName, messageContentObj.queueName);
        } else if (msgID == UpdateSystemPretestStatus) {
            updateColorButtonsVisible(messageContentObj.isPretest);
            refreshRightRegion();
        }else if(msgID=='STS_Update_System_NotTriage_Num'){
            var sysId =  getSystemId();
            if(sysId == messageContentObj.systemId&&$("#nptsplit_dia_ifram").length>0) $("#nptsplit_dia_ifram")[0].contentWindow.refreshTab();
        }else if(msgID=='STS_Update_Queue_NoSign_Num'){
            Reset_Queue_NoSign_Num_Nurse(messageContentObj.queueId,messageContentObj.noSignCount);
            refreshByRabbit(messageContentObj.queueId);
        }
        // //账号在其他终端登录
        // }else if (msgID == ForcedLoginOut) {
        //     Forced_LoginOut(messageContentObj.triageName, messageContentObj.positionStr,
        //         messageContentObj.ip);
        // }
    }

}

// 由MQ消息刷新列表
function refreshByRabbit(mqQueueId) {
    var queueId = getLocalQueueId();
    if (queueId == mqQueueId) {
        $("#patient_tmt_info")[0].contentWindow.refreshTab()
        console.log("刷新候诊/复诊/已就诊患者列表!!!！");
    }
}


//被迫退出
// function Forced_LoginOut(triageName,positionStr,ip) {
//     alert("您的账号"+triageName+"已在"+positionStr+"登录，ip为："+ip+"您已被迫下线！");
//     my_cefsharp. CefSharp_MainForm_Close();
// }


//重置队列在线状态 1-在线0-离线2-暂停
function Reset_Queue_OnLine_Nurse(sysId, queueId, onlineFlag) {
    alert(sysId + "_" + queueId + "_" + onlineFlag);
}

//页面全部加载完毕
$(window).load(function () {
    NProgress.done();
});

function loadUserInfo() {
    var deptName = getCookie("deptName");
    var name = getCookie("name");
    if (deptName == null) {
        deptName = "";
    }
    if (name == null) {
        name = "";
    }
    deptName = unescape(deptName);
    name = unescape(name);
    $("#dept_name_index").html(deptName);
    $("#name_index").html(name);
}

//加载分诊台系统类型
function loadCallSystemTypeList() {
    var _triageId = getLocalDeviceCookie("C_OR_T_ID") == null ? getDeviceId() : getLocalDeviceCookie("C_OR_T_ID");

    console.log('_triageId--->'+_triageId);

    $.ajax({
        url: _ReqCallSystemListUrl,
        data: {
            triageId: _triageId,
        },
        type: 'get',
        success: function (d) {
            if (JSON.parse(d).status == '0') {
                var dataInfo = JSON.parse(d).data;
                var _optionHtml ="<option>全部</option>";
                for (var i = 0; i < dataInfo.length; i++) {
                    var isPretestSystemId = dataInfo[i].isPretest+dataInfo[i].systemId;
                    localStorage.removeItem('0' + dataInfo[i].systemId)
                    localStorage.removeItem('1' + dataInfo[i].systemId)
                    localStorage.setItem(isPretestSystemId,dataInfo[i].isPretest);
                    _optionHtml += "<option value='" + dataInfo[i].systemId + "' data-deptId='" + dataInfo[i].deptId + "' data-preTest='" + dataInfo[i].isPretest + "'>" + dataInfo[i].systemName + "</option>";
                }
                $("#select_call_systemType").html(_optionHtml);
                _sysId = $("#select_call_systemType").find("option:eq(1)").prop("value");
                _sysDeptId = $("#select_call_systemType").find("option:eq(1)").attr("data-deptId");
               var allDataInfo = JSON.stringify(dataInfo);
                localStorage.setItem("allDataInfo", allDataInfo);
                var isonline= 'n';
                loadAllQueueLists(dataInfo,"list",isonline);
                if (dataInfo.length > 0) {
                    updateColorButtonsVisible(dataInfo[0].isPretest);
                }
            }
        }, complete: function () {
            localStorage.systemId = _sysId;
            localStorage.deptIdAll = _sysDeptId;
            //更新页面底部的候诊、过号、已就诊数量
            updateNumbers();
            // 系统加载完成后，默认加载第一个系统下的队列
            // loadDoctorQueueList("list");
        }
    });
}

//显示全部系统及系统下的队列
function  loadAllQueueLists(dataInfoList,listtype,isonline) {

    $("#d_left_center").hide();
    $("#_listcontent").html("");
    var _allSystemHtml= "";
    for(var i = 0; i < dataInfoList.length; i++){
        _allSystemHtml +="<div class='titleImg'>" +
            "<div class='title' data-deptId='"+dataInfoList[i].deptId+"' data-preTest='" + dataInfoList[i].isPretest + "' id='"+dataInfoList[i].systemId+ "'>"+
            "<p onclick='openOrClose(this)'><span>"+dataInfoList[i].systemName+"</span><img  id='"+dataInfoList[i].systemId+ "1' class='imgClick' src='./source/img/close.png'/></p>"+
            "<div class='listQuqueInfo listQuqueStatus'><span id='sysId_"+dataInfoList[i].systemId+"' data-preTest='" + dataInfoList[i].isPretest +"' data-deptId='"+dataInfoList[i].deptId+ "' data-systemId='"+dataInfoList[i].systemId+ "' type='button' class='d_left_center_button but_notsplitDiaOpt' onclick='notSplitDiaOptAll(\"" +0 + "\",\""+dataInfoList[i].systemId+"\",\""+dataInfoList[i].deptId+"\",\""+dataInfoList[i].isPretest+"\",\""+dataInfoList[i].greenChannel+"\");' >未分诊列表</span></div>"+
            "</div>" +
            "</div>";
    }
    $("#_listcontent").append(_allSystemHtml);
    getList(dataInfoList,listtype,isonline);
    $("#_listcontent").find('.titleImg:first-child img').attr('src','./source/img/open.png');
}
function getQueueInfo(currentIndex) {
    var dataInfoList = JSON.parse(localStorage.getItem("allDataInfo"));
    var isonline = 'n';
    var _contentHtml = "<div class='doctorlist_content'>";
    var firstCategory= null;
    var queueId,queueKey;
    var localQueueId = getLocalQueueId();
    $.ajax({
        url: _QueryQueueBySystemIdUrl,
        data: {
            queueStatus: '',
            systemId: dataInfoList[currentIndex].systemId
        },
        async: false,
        success: function (d) {
            if (JSON.parse(d).status == '0') {
                var dataInfo = JSON.parse(d).data;
                // 更新
                updateGreenChannelVisible(dataInfo.greenChannel);

                var isChecked = $('#chk_online').is(":checked");
                // 是否开启优先类别 选择，0：关闭，1：开启（2.10新增）
                firstCategory = dataInfo.firstCategory;
                for (var i = 0; i < dataInfo.qcQueueList.length; i++) {
                    //队列类型(普通队列1、专家队列2)
                    if(isChecked&&dataInfo.qcQueueList[i].queueStatus == '2') continue;
                    //队列id
                    var _queueId = dataInfo.qcQueueList[i].queueId;
                    //医生照
                    var _workingPicture = dataInfo.qcQueueList[i].workingPicture;
                    //科室名称
                    var _deptMing = dataInfo.qcQueueList[i].deptMing;
                    //候诊数量
                    var _waitTreatCount = dataInfo.qcQueueList[i].waitTreatCount;
                    //已就诊数量
                    var _treatedCount = dataInfo.qcQueueList[i].treatedCount;
                    //过号数量
                    var _overFlowCount = dataInfo.qcQueueList[i].overFlowCount;
                    // 未报到数量
                    var _noSignCount = 'noSignCount' in dataInfo.qcQueueList[i]?dataInfo.qcQueueList[i].noSignCount:0;
                    //队列名称
                    var _queueName = dataInfo.qcQueueList[i].queueName;
                    //队列key
                    var _queueKey = dataInfo.qcQueueList[i].queueKey;
                    //在线离线
                    var _queueStatus = dataInfo.qcQueueList[i].queueStatus == "0" ? "ZX"
                        : dataInfo.qcQueueList[i].queueStatus == '1' ? "ZT"
                            : dataInfo.qcQueueList[i].queueStatus == '2' ? "p" : "LX";
                    //第一个系统第一个队列
                    if (currentIndex == 0){
                        if(i == 0) {
                            queueId = _queueId;
                            queueKey = _queueKey;
                        }
                    }

                    //在线状态
                    var imghtm = "";
                    if (_queueStatus == "ZX") {
                        queueId2StatusMap[_queueId] = 0;
                    } else if (_queueStatus == "ZT") {
                        queueId2StatusMap[_queueId] = 1;
                    } else if (_queueStatus == "LX") {
                        queueId2StatusMap[_queueId] = 2;
                    } else {
                        queueId2StatusMap[_queueId] = 2;
                    }
                    // alert(_queueStatus+"aa");
                    //是否只显示在线

                    if (isonline == 'y') {
                        if (_queueStatus != "ZX")
                            continue;
                    }
                    //列表展示
                        var isonline_css = _queueStatus == 'ZX' ? "list_doctor_online" :
                            _queueStatus == 'LX' ? "list_doctor_offline" :
                                _queueStatus == 'ZT' ? "list_doctor_stoped" : "list_doctor_offline";
                        if(localQueueId==_queueId){
                            _contentHtml += "<div  class='items "+isonline_css+"' onclick='queryQueuePatientsForListAll(this,\""+ dataInfo.greenChannel +"\")' data-firstCategory='"+firstCategory+"' data-firstCategory='"+firstCategory+"'  data-queueId='" +
                                _queueId + "' data-queueKey='" + _queueKey + "' data-greenchannel='"+dataInfo.greenChannel+"' id='qid_"+ _queueId +"' style='background-color:#F3F9FF;'><span  id=" + _queueId + "_text" + " title=" + _deptMing + "&nbsp" + _queueName + " class='queueNameStyle " + isonline_css + "'>" +
                                _queueName +
                                "</span><span class='mui-status queueStatus-"+dataInfo.qcQueueList[i].queueStatus+"''>"
                                + "</span><ul class='clearfix mui-tatol'><li>候诊：<span class='waitCount'>"+_waitTreatCount+"</span></li><li>过号：<span class='overCount'>"+_overFlowCount+"</span></li><li>已就诊：<span class='endCount'>"+_treatedCount+"</span></li><li style='display: none'>未报到：<span class='noSignCount'>"+_noSignCount+"</span></li></ul></div>";
                        }else {
                            _contentHtml += "<div class='items "+isonline_css+"' onclick='queryQueuePatientsForListAll(this,\""+ dataInfo.greenChannel +"\")' data-firstCategory='"+firstCategory+"' data-firstCategory='"+firstCategory+"'  data-queueId='" +
                                _queueId + "' data-queueKey='" + _queueKey + "' data-greenchannel='"+dataInfo.greenChannel+"' id='qid_"+ _queueId +"'><span  " + "id=" + _queueId + "_text" + " title=" + _deptMing + "&nbsp" + _queueName + " class='queueNameStyle " + isonline_css + "'>" +
                                _queueName +
                                "</span><span class='mui-status queueStatus-"+dataInfo.qcQueueList[i].queueStatus+"'></span>"
                                +"<ul class='clearfix mui-tatol'><li>候诊：<span class='waitCount'>"+_waitTreatCount+"</span></li><li>过号：<span class='overCount'>"+_overFlowCount+"</span></li><li>已就诊：<span class='endCount'>"+_treatedCount+"</span></li><li  style='display: none'>未报到：<span class='noSignCount'>"+_noSignCount+"</span></li></ul></div>";
                        }

                }
                _contentHtml += "</div>";
                $("#" + dataInfoList[currentIndex].systemId).append(_contentHtml);
                //获取到默认选中第一个队列的绿色通道参数值
                localStorage.greenChannel =  $(".titleImg").find(".doctorlist_content").find("div").data("greenchannel");
                _contentHtml = "";
            }

        }
    });
}
function getList(dataInfoList,listtype,isonline) {
    var currentIndex = 0;
    cancelButtonClick();
    var _contentHtml = "<div class='doctorlist_content'>";

    var preTest = $("#select_call_systemType").find("option:eq(1)").attr("data-preTest");
    updateColorButtonsVisible(preTest);
    //默认加载的第一条队列ID
    var queueId = -1;
    var firstCategory= null;
    var queueKey = "";  // 队列的key
    var queueStatus = isonline == "y" ? "0" : "";
    var _loadIndex = null;
    $.ajax({
        url: _QueryQueueBySystemIdUrl,
        data: {
            queueStatus: queueStatus,
            systemId: dataInfoList[currentIndex].systemId
        },
        async: false,
        success: function (d) {
            if (JSON.parse(d).status == '0') {
                parent.layer.close(_loadIndex);
                // $("#_listcontent").html("");
                var dataInfo = JSON.parse(d).data;
                // 更新
                updateGreenChannelVisible(dataInfo.greenChannel);
                var isChecked = $('#chk_online').is(":checked");
                // 是否开启优先类别 选择，0：关闭，1：开启（2.10新增）
                firstCategory = dataInfo.firstCategory;
                for (var i = 0; i < dataInfo.qcQueueList.length; i++) {
                    if(isChecked&&dataInfo.qcQueueList[i].queueStatus == '2') continue;
                    //队列类型(普通队列1、专家队列2)
                    //队列id
                    var _queueId = dataInfo.qcQueueList[i].queueId;
                    //医生照
                    var _workingPicture = dataInfo.qcQueueList[i].workingPicture;
                    //科室名称
                    var _deptMing = dataInfo.qcQueueList[i].deptMing;
                    //候诊数量
                    var _waitTreatCount = dataInfo.qcQueueList[i].waitTreatCount;
                    //已就诊数量
                    var _treatedCount = dataInfo.qcQueueList[i].treatedCount;
                    //过号数量
                    var _overFlowCount = dataInfo.qcQueueList[i].overFlowCount;
                    // 未报到数量
                    var _noSignCount = 'noSignCount' in dataInfo.qcQueueList[i]?dataInfo.qcQueueList[i].noSignCount:0;
                    //队列名称
                    var _queueName = dataInfo.qcQueueList[i].queueName;
                    //队列key
                    var _queueKey = dataInfo.qcQueueList[i].queueKey;
                    //在线离线
                    var _queueStatus = dataInfo.qcQueueList[i].queueStatus == "0" ? "ZX"
                        : dataInfo.qcQueueList[i].queueStatus == '1' ? "ZT"
                            : dataInfo.qcQueueList[i].queueStatus == '2' ? "p" : "LX";
                    //第一个系统第一个队列
                    if (currentIndex == 0){
                        if(i == 0) {
                            queueId = _queueId;
                            queueKey = _queueKey;
                        }
                    }
                    if (_queueStatus == "ZX") {
                        queueId2StatusMap[_queueId] = 0;
                    } else if (_queueStatus == "ZT") {
                        queueId2StatusMap[_queueId] = 1;
                    } else if (_queueStatus == "LX") {
                        queueId2StatusMap[_queueId] = 2;
                    } else {
                        queueId2StatusMap[_queueId] = 2;
                    }
                    // alert(_queueStatus+"aa");
                    //是否只显示在线

                    if (isonline == 'y') {
                        if (_queueStatus != "ZX")
                            continue;
                    }
                    var isonline_css = _queueStatus == 'ZX' ? "list_doctor_online" :
                        _queueStatus == 'LX' ? "list_doctor_offline" :
                            _queueStatus == 'ZT' ? "list_doctor_stoped" : "list_doctor_offline";

                    _contentHtml += "<div class='items "+isonline_css+"' onclick='queryQueuePatientsForListAll(this,\""+ dataInfo.greenChannel +"\")' data-firstCategory='"+firstCategory+"' data-firstCategory='"+firstCategory+"'  data-queueId='" +
                        _queueId + "' data-queueKey='" + _queueKey + "' data-greenchannel='"+dataInfo.greenChannel+"' id='qid_"+ _queueId +"' ><span  " + "id=" + _queueId + "_text" + " title=" + _deptMing + "&nbsp" + _queueName + " class='queueNameStyle " + isonline_css + "'>" +
                        _queueName +
                        "</span><span class='mui-status queueStatus-"+ dataInfo.qcQueueList[i].queueStatus+"'></span>"
                        +"<ul class='clearfix mui-tatol'><li>候诊：<span class='waitCount'>"+_waitTreatCount+"</span></li><li>过号：<span class='overCount'>"+_overFlowCount+"</span></li><li>已就诊：<span class='endCount'>"+_treatedCount+"</span></li><li style='display: none'>未报到：<span class='noSignCount'>"+_noSignCount+"</span></li></ul></div>";
                }
                _contentHtml += "</div>";
                $("#" + dataInfoList[currentIndex].systemId).append(_contentHtml);
                //获取到默认选中第一个队列的绿色通道参数值
                localStorage.greenChannel = $(".titleImg").find(".doctorlist_content").find("div").data("greenchannel");
                _contentHtml = "";
                currentIndex++;
            }

        }, complete: function () {

            $("#div_switchgroup").css({ "pointer-events": "all" });
            $("#d_left_op_bottom").css({ "pointer-events": "all" });
            // 将队列id送到本地缓存
            localStorage.firstCategory = firstCategory;
            localStorage.queueId = queueId;
            localStorage.queueKey = queueKey;
            $('#'+queueId + "_text").parent().addClass('itemsActive');
            // 更新显示右侧区域显示内容
            refreshRightRegion();
            //告诉c端，页面准备完毕
            try { my_cefsharp.Begin_Receive_RabbitMQ_Nurse(); } catch (err) { }

        }
    });
}
function openOrClose(that){
    if($(that).find('img').attr("src")=="./source/img/open.png"){
        $(that).parents('.titleImg').find('.listQuqueInfo').hide();
        $(that).find('img').attr("src","./source/img/close.png");
        $(that).parents('.titleImg').find('.doctorlist_content').remove();
    } else{
        var idx = $(that).parents('.titleImg').index();
        getQueueInfo(idx);
        $(that).parents('.titleImg').find('.listQuqueInfo').show();
        $(that).find('img').attr("src","./source/img/open.png");
    }
}

//切换到设置密码
function linkEditPwd() {
    window.location.href = "./setting/edit_pwd.html";
}

//切换排班分诊界面
/*function switch_p_p() {

    console.log('1');
    $("[name='switch_p_or_p']").bootstrapSwitch({
        onText: "分诊",
        offText: "排班",
        size: "small",
        animate: false,
        offColor: "primary",
        onSwitchChange: function (e, s) {
            if (s) {
                console.log("切换到分诊");
                $(".bootstrap-switch-label").text("排班");

                // 重新加载页面
                loadTheFristPage();

                try { my_cefsharp.Set_PageKeyFlag_Cef("Patient.nurse"); } catch (err) { }

            } else {
                //切换到排版
                console.log("切换到排班");
                $(".bootstrap-switch-label").text("分诊");
                window.location.href = './arrange/arrange_list.html';
                try { my_cefsharp.Set_PageKeyFlag_Cef("Patient.nurse"); } catch (err) { }
                ////加载排版页面
            }
        },
    });
}*/

/**
 * 加载系统下满足条件的队列
 * 条件包括:
 *  listType: expend(图标)，list(列表)
 *  isonline: y(在线)，n(离线)
 */
function loadQueuesBySystem() {
    var systemId = $("#select_call_systemType").val();
    var dataInfoList = JSON.parse(localStorage.getItem("allDataInfo"));
    if ($("#chk_online").prop("checked")) {
        if(systemId == "全部"){
            localStorage.systemId = $("#select_call_systemType").find("option:eq(1)").prop("value");
            localStorage.deptIdAll = $("#select_call_systemType").find("option:eq(1)").attr("data-deptId");
            loadAllQueueLists(dataInfoList,listType,"y");
        } else {
            localStorage.systemId = $("#select_call_systemType").val();
            localStorage.deptIdAll = $("#select_call_systemType option:selected").attr("data-deptId");
            loadDoctorQueueList(listType, "y");

        }
    } else {
        if(systemId == "全部"){
            localStorage.systemId = $("#select_call_systemType").find("option:eq(1)").prop("value");
            localStorage.deptIdAll = $("#select_call_systemType").find("option:eq(1)").attr("data-deptId");
            loadAllQueueLists(dataInfoList,listType,"n");
        } else {
            localStorage.systemId = $("#select_call_systemType").val();
            localStorage.deptIdAll = $("#select_call_systemType option:selected").attr("data-deptId");
            loadDoctorQueueList(listType, "n");
        }
    }
    //切换系统时更新底部候诊及其他数量

    updateNumbers();
}

/**
 * 加载医生队列列表
 * @param listtype 取值返回: list；expend
 * @param isonline 是否在线：y-在线；n-离线
 */
function loadDoctorQueueList(listtype, isonline) {
    cancelButtonClick();
    $("#d_left_center").show();
    $("#_listcontent").html("");
    var _contentHtm = "<div class='doctorlist_content'>";
    _sysId = allOrSingleSystemId();
    _sysDeptId = $("#select_call_systemType option:selected").attr("data-deptId");
    var preTest = $("#select_call_systemType option:selected").attr("data-preTest");
    updateColorButtonsVisible(preTest);
    //默认加载的第一条队列ID
    var queueId = -1;
    var queueKey = "";  // 队列的key
    var queueStatus = isonline == "y" ? "0" : "";
    var _loadIndex = null;
    $.ajax({
        url: _QueryQueueBySystemIdUrl,
        data: {
            queueStatus: queueStatus,
            systemId: _sysId
        },
        beforeSend: function () {
            _loadIndex = layer.msg("加载中...", { icon: 16 });
            $("#div_switchgroup").css({ "pointer-events": "none" });
            $("#d_left_op_bottom").css({ "pointer-events": "none" });
        },
        success: function (d) {
            if (JSON.parse(d).status == '0') {

                parent.layer.close(_loadIndex);
                $("#_listcontent").html("");

                var dataInfo = JSON.parse(d).data;
                // 更新
                updateGreenChannelVisible(dataInfo.greenChannel);
                // 是否开启优先类别 选择，0：关闭，1：开启（2.10新增）
                var firstCategory = dataInfo.firstCategory;
                for (var i = 0; i < dataInfo.qcQueueList.length; i++) {

                    //队列类型(普通队列1、专家队列2)
                    //队列id
                    var _queueId = dataInfo.qcQueueList[i].queueId;
                    //医生照
                    var _workingPicture = dataInfo.qcQueueList[i].workingPicture;
                    //科室名称
                    var _deptMing = dataInfo.qcQueueList[i].deptMing;
                    //候诊数量
                    var _waitTreatCount = dataInfo.qcQueueList[i].waitTreatCount;
                    //已就诊数量
                    var _treatedCount = dataInfo.qcQueueList[i].treatedCount;
                    //过号数量
                    var _overFlowCount = dataInfo.qcQueueList[i].overFlowCount;
                    //队列名称
                    var _queueName = dataInfo.qcQueueList[i].queueName;
                    //队列key
                    var _queueKey = dataInfo.qcQueueList[i].queueKey;
                    //在线离线
                    var _queueStatus = dataInfo.qcQueueList[i].queueStatus == "0" ? "ZX"
                        : dataInfo.qcQueueList[i].queueStatus == '1' ? "ZT"
                            : dataInfo.qcQueueList[i].queueStatus == '2' ? "p" : "LX";

                    if (i == 0) {
                        queueId = _queueId;
                        queueKey = _queueKey;
                    }
                    //在线状态
                    var imghtm = "";
                    if (_queueStatus == "ZX") {
                        queueId2StatusMap[_queueId] = 0;
                    } else if (_queueStatus == "ZT") {
                        queueId2StatusMap[_queueId] = 1;
                    } else if (_queueStatus == "LX") {
                        queueId2StatusMap[_queueId] = 2;
                    } else {
                        queueId2StatusMap[_queueId] = 2;
                    }

                    //是否只显示在线
                    if (isonline == 'y') {
                        if (_queueStatus != "ZX")
                            continue;
                    }
                    var isonline_css = _queueStatus == 'ZX' ? "list_doctor_online" :
                        _queueStatus == 'LX' ? "list_doctor_offline" :
                            _queueStatus == 'ZT' ? "list_doctor_stoped" : "list_doctor_offline";

                    _contentHtm += "<div class='items "+isonline_css+"' onclick='queryQueuePatientsForList(this)' data-firstCategory='"+firstCategory+"' data-queueId='" +
                        _queueId + "' data-queueKey='" + _queueKey + "'><span  " + "id=" + _queueId + "_text" + " title=" + _deptMing + "&nbsp" + _queueName + " class='queueNameStyle " + isonline_css + "'>" +
                        _deptMing + "&nbsp" + _queueName +
                        "</span><span class='mui-status queueStatus-"+dataInfo.qcQueueList[i].queueStatus+"'></span>"
                        +"<ul class='clearfix mui-tatol'><li>候诊：<span>"+_waitTreatCount+"</span></li><li>过号：<span>"+_overFlowCount+"</span></li><li>已就诊：<span>"+_treatedCount+"</span></li></ul></div>";


                }

                _contentHtm += "</div>";
                $("#_listcontent").append(_contentHtm);

            }
        }, complete: function () {

            $("#div_switchgroup").css({ "pointer-events": "all" });
            $("#d_left_op_bottom").css({ "pointer-events": "all" });
            // 将队列id送到本地缓存
            localStorage.queueId = queueId;
            localStorage.queueKey = queueKey;
            //默认加载第一个队列后显示选择样式
            $('#'+queueId + "_text").parent().addClass('itemsActive');

            // 更新显示右侧区域显示内容
            refreshRightRegion();
            //告诉c端，页面准备完毕
            try { my_cefsharp.Begin_Receive_RabbitMQ_Nurse(); } catch (err) {

            }

        }
    });
}
function firstQueueStyle(){

}
/**
 * 当修改下拉框时，刷新分诊台右侧区域
 * @param selectedQueueId 选中的队列id
 */
function refreshRightRegion() {
    // 加载静态页面
    var mainheight = $("#d_left").css("height");
    $('#d_right_content').html('<iframe scrolling="no" id="patient_tmt_info" src="./nurse_mgr/patient_tmt_info.html" style="width:100%;border:none;height:100%;"></iframe>');
}

//取消为分诊列表选中状态
function cancelButtonClick() {
    changeNotSplitDiaOptStyle();
}

function test() {
    alert("test");
    Reset_STS_Update_Queue_Status(null, "50569e69da3441f8bf0082677acb2d1d", 1, "list");
}

//更新候诊、过号、已就诊
function updateNumbers() {
    var systemId = allOrSingleSystemId();
    $.ajax({
        url: _UpdateNumbers,
        data: {
            systemId: systemId
        },
        type: 'get',
        success: function (d) {
            if (JSON.parse(d).status == '0') {
                var dataInfo = JSON.parse(d).data;
                var waitNum = dataInfo.waitTreatCount;
                var overFlow = dataInfo.overFlowCount;
                var treate = dataInfo.treatedCount;
                $("#m_span_hz").html(waitNum);
                $("#m_span_gh").html(overFlow);
                $("#m_span_yjz").html(treate);
            } else {
                layer.msg(JSON.parse(d).desc);
            }
        }
    });
}
//全部时更新候诊、过号、已就诊
function updateNumbersAll(systemId) {
    $.ajax({
        url: _UpdateNumbers,
        data: {
            systemId: systemId
        },
        type: 'get',
        success: function (d) {
            if (JSON.parse(d).status == '0') {
                var dataInfo = JSON.parse(d).data;
                var waitNum = dataInfo.waitTreatCount;
                var overFlow = dataInfo.overFlowCount;
                var treate = dataInfo.treatedCount;
                $("#m_span_hz").html(waitNum);
                $("#m_span_gh").html(overFlow);
                $("#m_span_yjz").html(treate);
            } else {
                layer.msg(JSON.parse(d).desc);
            }
        }
    });
}
//全部时点击未分诊列表
function notSplitDiaOptAll(d,_sysId,_sysDeptId,_preTest,_greenChannel) {
    changeNotSplitDiaOptStyle(d,_sysId);
    $(".expand_conent").css({"border": "1px solid #CCCCCC"});
    localStorage.systemId = _sysId;
    localStorage.deptIdAll = _sysDeptId;
    updateColorButtonsVisible(_preTest);//预检选项按钮
    updateNumbersAll(_sysId);
    //加载未分诊页面
    var url = "./nurse_mgr/notsplit_dia.html?systemId=" + _sysId + "&deptId=" + _sysDeptId+ "&greenChannel=" + _greenChannel;
    $('#d_right_content').html('<iframe scrolling="no" id="nptsplit_dia_ifram" name="nptsplit_dia_ifram" frameborder="1" style="width:100%;border:none;height:100%;"></iframe>');
    window.open(url, 'nptsplit_dia_ifram');

}

//未分诊队列
function notSplitDiaOpt(d) {
    changeNotSplitDiaOptStyle(d);
    //取消队列选中样式
    $("#_listcontent div").css({ "background-color": "#ffffff" });
    $(".expand_conent").css({"border": "1px solid #CCCCCC"});
    //加载未分诊页面
    var url = "./nurse_mgr/notsplit_dia.html?systemId=" + _sysId + "&deptId=" + _sysDeptId;
    $("#d_right_content").html("");

    var mainheight = $("#d_left").css("height");

    $('#d_right_content').append('<iframe scrolling="no" id="nptsplit_dia_ifram" name="nptsplit_dia_ifram" frameborder="1" style="width:100%;border:none;height:100%;"></iframe>');
    window.open(url, 'nptsplit_dia_ifram');

}

//医生患者信息
function queryQueuePatientsForList(_this) {
    cancelButtonClick();
    //切换样式
    loadSimpleDocTypeHeaderStype(_this);
    loadSelectedQueuePatients(_this);
    var firstCategory = $(_this).attr("data-firstCategory");
    localStorage.firstCategory = firstCategory;
}
/***
 * 分诊台系统显示全部点击队列名称加载内容
 * 这里是列表模式
 ***/
function queryQueuePatientsForListAll(_this,_greenChannel) {
    cancelButtonClick();
    //切换样式
    loadSimpleDocTypeHeaderStype(_this);
    var preTest = $(_this).parent().parent().attr("data-preTest");
    var systemId = $(_this).parent().parent().attr("id");
    var deptId = $(_this).parent().parent().attr("data-deptId");
    var firstCategory = $(_this).attr("data-firstCategory");
    localStorage.firstCategory = firstCategory;
    localStorage.systemId = systemId;
    localStorage.deptIdAll = deptId;
    localStorage.greenChannel = _greenChannel;
    loadSelectedQueuePatients(_this,"all");
    updateNumbersAll(systemId);
    updateColorButtonsVisible(preTest);
}
/**
 * 全部页面医生患者信息 展开模式
 *  这里是图文模式
 **/
function queryQueuePatientsForExpandAll(_this) {
    cancelButtonClick();
    //切换样式
    change_expandborder_color(_this);
    var preTest = $(_this).parent().parent().parent().attr("data-preTest");
    var systemId = $(_this).parent().parent().parent().attr("id");
    var deptId = $(_this).parent().parent().parent().attr("data-deptId");
    var firstCategory = $(_this).attr("data-firstCategory");
    localStorage.firstCategory = firstCategory;
    localStorage.systemId = systemId;
    localStorage.deptIdAll = deptId;

    loadSelectedQueuePatients(_this,"all");
    updateNumbersAll(systemId);
    updateColorButtonsVisible(preTest);
}
//医生患者信息 展开模式
function queryQueuePatientsForExpand(_this) {
    cancelButtonClick();
    var firstCategory = $(_this).attr("data-firstCategory");
    localStorage.firstCategory = firstCategory;
    //切换样式
    change_expandborder_color(_this);
    loadSelectedQueuePatients(_this);
}

/**
 * 重新加载选中队列的患者信息
 * @param _this
 */
function loadSelectedQueuePatients(_this,type) {
    // 获取队列id
    if(type != "all"){
        localStorage.systemId = allOrSingleSystemId();
    }
    _selectedQueueId = $(_this).attr("data-queueId");
    console.log('_selectedQueueId----'+_selectedQueueId)
    localStorage.queueId = _selectedQueueId;
    localStorage.queueKey = $(_this).attr("data-queueKey");
    //获取医生ID
    //$("#d_right_content").load("./nurse_mgr/patient_tmt_info.html");
    var mainheight = $("#d_left").css("height");
    $('#d_right_content').html('<iframe scrolling="no" id="patient_tmt_info" src="./nurse_mgr/patient_tmt_info.html" style="width:100%;border:none;height:100%;"></iframe>');
}

//平铺展示
function rd_op_expand(t) {
    listType = $("#doctor_expand").attr("attr");
    $("#_listcontent").html("");
    var systemId = $("#select_call_systemType").val();
    var dataInfoList = JSON.parse(localStorage.getItem("allDataInfo"));
    $("#but_doctor_list").css({ "background-color": "transparent" });
    $(t).css({
        "background-color": "#ABA7A6"
    });

    if ($("#chk_online").prop("checked")) {
        if(systemId == "全部"){
            loadAllQueueLists(dataInfoList,listType,"y");
        } else {
            loadDoctorQueueList(listType, "y");
        }
    } else {
        if(systemId == "全部"){
            loadAllQueueLists(dataInfoList,listType,"n");
        } else {
            loadDoctorQueueList(listType, "n");
        }
    }
    $("#but_doctor_list").children("img").attr("src", "source/img/menuList-grey.png")
    $("#but_doctor_expand").children("img").attr("src", "source/img/menu.png")
}

//列表展示
function rd_op_list(t) {
    listType = $("#doctor_list").attr("attr");
    $("#_listcontent").html("");
    var systemId = $("#select_call_systemType").val();
    var dataInfoList = JSON.parse(localStorage.getItem("allDataInfo"));
    $(t).css({
        "background-color": "#ABA7A6"
    });
    $("#but_doctor_expand").css({ "background-color": "transparent" });
    if ($("#chk_online").prop("checked")) {
        if(systemId == "全部"){
            loadAllQueueLists(dataInfoList,listType,"y");
        } else {
            loadDoctorQueueList(listType, "y");
        }
    } else {
        if(systemId == "全部"){
            loadAllQueueLists(dataInfoList,listType,"n");
        } else {
            loadDoctorQueueList(listType, "n");
        }
    }
    $("#but_doctor_list").children("img").attr("src", "source/img/menuList.png");
    $("#but_doctor_expand").children("img").attr("src", "source/img/menu-grey.png");
}

/**
 * 判断队列是否离线，当队列的状态是2时，表示队列离线
 * @param queueId
 * @returns {boolean}
 */
function checkQueueIsOffline(opQueueId) {
    if (queueId2StatusMap[opQueueId] == 2)
        return true;
    else
        return false;
}

/**
 * 更新“绿色通道”按钮是否需要显示的标识
 * @param show, 1- 显示； 0-不显示
 */
function updateGreenChannelVisible(show) {
    localStorage.greenChannel = show;
}

/**
 * 获取“绿色通道”按钮的显示状态
 * @returns {*}
 */
function showGreenChannelButton() {
    return localStorage["greenChannel"] == 1;
}

/**
 * 更新“预检颜色”按钮是否显示
 * @param show
 */
function updateColorButtonsVisible(show) {
    localStorage.colorStatus = show;
}

/**
 * 是否显示“预检颜色”按钮
 * @returns {boolean}
 */
function showColorButtons() {
    return localStorage["colorStatus"] == 1;
}
//c端给b端传值，调的方法
function Read_Batch_Card_Info_notsplit_nurse(patientKey) {
    $("#bulkPageTmt iframe")[0].contentWindow.passCardToBatch(patientKey);
}
//判断是全部还是选中系统
function allOrSingleSystemId(){
    return localStorage["systemId"];
}

//全部还是选中某个系统的科室
function allOrSingleDeptId(){
    var deptId = "";
    var systemId = $("#select_call_systemType").val();
    var localDept = localStorage["deptIdAll"];
    if(systemId == "全部"){
        if(localDept != "" ||localDept != undefined || localDept != null) {
            deptId = localDept;
        }else{
            deptId = $("#select_call_systemType").find("option:eq(1)").attr("data-deptId");
        }
    } else {
        deptId = $("#select_call_systemType option:selected").attr("data-deptId");
    }
    return deptId;
}
